package cn.i96688.scanclient.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;

import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.i96688.scanclient.bean.PayLog;
import cn.i96688.scanclient.bean.Status;
import cn.i96688.scanclient.service.ScanPayService;
import cn.i96688.scanclient.service.impl.ScanPayServiceImpl;
import cn.i96688.scanclient.utils.Constants;

/**
 * 当日的订单
 * 
 * @author xys
 *
 */
@SuppressWarnings("serial")
public class CurOrderListPane extends SuperPane {
	private ScanPayService scanService = new ScanPayServiceImpl();
	private JTable orderTable = null;
	private HYBTableModel orderModel = null;
	private JScrollPane orderScroll = null;
	private JPopupMenu popupMenu=null;
	public final static int INDEX_ORDER_NO=0;
	public final static int INDEX_PAYABLE=1;
	public final static int INDEX_EXCHANGE=2;
	public final static int INDEX_STATUS=3;
	
	private final String[] columnNames = { "订单号", "付款金额（元）","交易时间", "交易状态" };
	
	public CurOrderListPane() {
		setLayout(new BorderLayout());
		orderModel = new HYBTableModel();
		orderTable = new JTable(orderModel) {
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		orderScroll = new JScrollPane(orderTable);
		add(orderScroll, BorderLayout.CENTER);
		orderTable.setRowHeight(25);
		orderTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		orderTable.setFillsViewportHeight(true);
		orderModel.init();

		TableColumnModel colModel = orderTable.getColumnModel();
		TableColumn colOrderNo = colModel.getColumn(0);
		TableColumn colPayable = colModel.getColumn(1);
		TableColumn colPayTime = colModel.getColumn(2);
		TableColumn colStatus = colModel.getColumn(3);
		colStatus.setCellRenderer(new StatusRender());

		colOrderNo.setPreferredWidth(200);
		colPayable.setPreferredWidth(100);
		colPayTime.setPreferredWidth(200);
		colStatus.setPreferredWidth(100);
		
		createPopupMenu();

		orderTable.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				mouseRightButtonClick(evt);
			}
		});
	}
	
	public void loadData(){
		orderModel.loadData();
	}
	
	public void addTableModelListener(TableModelListener l){
		orderModel.addTableModelListener(l);
	}
	
	public void insertRowFirst(JSONObject orderJson){
		orderModel.insertRowFirst(orderJson);
	}
	
	public void refresh(){
		while(orderModel.getRowCount()>0)
			orderModel.removeRow(0);
		orderModel.loadData();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		int row = orderTable.getSelectedRow();
		String orderNo = orderTable.getValueAt(row, 0).toString();
		JSONObject orderJson = scanService.queryOrder(orderNo);
		if(Status.isFail(orderJson)){
			return;
		}
		String exchangeTime = orderJson.getString("exchangeTime");
		String orderStatus = orderJson.getString("orderStatus");
		orderTable.setValueAt(exchangeTime, row, 2);
		orderTable.setValueAt(orderStatus, row, 3);
	}

	// 鼠标右键点击事件
	private void mouseRightButtonClick(java.awt.event.MouseEvent evt) {
		// 判断是否为鼠标的BUTTON3按钮，BUTTON3为鼠标右键
		/*
		 * 触摸屏，不能用右键
		if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
			
		}*/
		// 通过点击位置找到点击为表格中的行
		int focusedRowIndex = orderTable.rowAtPoint(evt.getPoint());
		if (focusedRowIndex == -1) {
			return;
		}
		// 将表格所选项设为当前右键点击的行
		orderTable.setRowSelectionInterval(focusedRowIndex, focusedRowIndex);
		//支付中，才能弹出
		Object status=orderTable.getValueAt(focusedRowIndex, 3);
		if(Constants.ORDER_PENDING.equals(status)){
			// 弹出菜单
			popupMenu.show(orderTable, evt.getX(), evt.getY());
		}			

	}

	private void createPopupMenu() {
		popupMenu = new JPopupMenu();

		JMenuItem refreshMenItem = new JMenuItem();
		refreshMenItem.setText("刷新订单数据 ");
		refreshMenItem.addActionListener(this);
		popupMenu.add(refreshMenItem);
	}

	class HYBTableModel extends DefaultTableModel {
		

		public void init() {
			this.setColumnIdentifiers(columnNames);
		}
		void loadData(){
			JSONObject datas = scanService.queryOrders();
			if (Status.isFail(datas)) {
				PayLog.getInstance().addLog("获取当前日期订单出错："
						+ datas.getString(Status.NAME_MSG));
				return;
			}
			JSONArray orders = datas.getJSONArray(Status.DATA);
			for (int i = 0; i < orders.size(); i++) {
				JSONObject orderJson = orders.getJSONObject(i);
				addRow(orderJson);
			}
		}
		void addRow(JSONObject orderJson){
			Object[] rowData = new Object[columnNames.length];
			rowData[INDEX_ORDER_NO] = orderJson.getString("orderNo");
			rowData[INDEX_PAYABLE] = orderJson.getString("payableAmount");
			rowData[INDEX_EXCHANGE] = orderJson.getString("exchangeTime");
			rowData[INDEX_STATUS] = orderJson.getString("orderStatus");
			this.addRow(rowData);
		}
		void insertRowFirst(JSONObject orderJson){
			Object[] rowData = new Object[columnNames.length];
			rowData[INDEX_ORDER_NO] = orderJson.getString("orderNo");
			rowData[INDEX_PAYABLE] = orderJson.getString("payableAmount");
			rowData[INDEX_EXCHANGE] = orderJson.getString("exchangeTime");
			rowData[INDEX_STATUS] = orderJson.getString("orderStatus");
			this.insertRow(0,rowData);
		}
	}

	class StatusRender implements TableCellRenderer {
		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			String status = value.toString();
			Color color=Color.BLACK;
			if (status.equals(Constants.ORDER_WAITING)) {
				status = "待支付";
			} else if (status.equals(Constants.ORDER_SUCCESS)) {
				status = "成功";
				color=Color.GREEN;
			} else if (status.equals(Constants.ORDER_PENDING)) {
				status = "支付中";
				color=Color.BLUE;
			} else {
				status = "失败";
				color=Color.RED;
			}
			JLabel comp = new JLabel(status);
			comp.setForeground(color);
			return comp;
		}

	}
}
